package growth.net.p2p;



import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class SendingService {

    private static SendingService sendingService;
    public int sendingPort;
    public DatagramSocket sendingSocket;

    public static SendingService getSendingService() {
        if (SendingService.sendingService == null) {
            SendingService.sendingService = new SendingService();
        }
        return sendingService;
    }

    private SendingService() {
        this.setupSendingSocket();
    }

    private void setupSendingSocket() {
        this.sendingPort = (int) (Math.random() * 9999) + 1000;
        if ((this.sendingPort > 9999) && (this.sendingPort < 1000)) {
            this.setupSendingSocket();
        }
        try {
            this.sendingSocket = new DatagramSocket(sendingPort);
            System.out.println("Send PORT :" + sendingPort);
        } catch (SocketException e) {
            System.out.println("Socket error: Trying another port");
            setupSendingSocket();
        }

    }

    public void send(String message, InetAddress ip, int toPort)
            throws Exception {
        byte[] sendData = new byte[1024];
        sendData = message.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData,
                sendData.length, ip, toPort);
        sendingSocket.send(sendPacket);

    }
}
